package com.spring.component.exception;

import java.util.List;
import java.util.Map;

import org.springframework.http.HttpStatus;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.pagehelper.PageInfo;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @author fanfever
 * @email fanfeveryahoo@gmail.com
 * @url https://github.com/fanfever
 * @date 2016年8月12日
 */
@Data
@JsonInclude(value = Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class BaseResponse<T> {

	/**
	 * 响应编码
	 */
	private int code;
	/**
	 * 响应消息
	 */
	private String message;
	private BaseException exception;
	/**
	 * 分页对象
	 */
	private Paging paging;
	/**
	 * 业务对象
	 */
	private T data;
	/**
	 * 跳转地址
	 */
	private String location;

	@JsonProperty("extra")
	private Map<String, ?> extraMap;

	public BaseResponse() {
		this(null);
	}

	public BaseResponse(T t) {
		this(t, null);
	}

	public BaseResponse(T t, Map<String, ?> extraMap) {
		if (null == t) {
			this.code = HttpStatus.OK.value();
			this.message = HttpStatus.OK.name();
		} 
//		else if (t instanceof BaseModel) {
//			this.code = HttpStatus.OK.value();
//			this.message = HttpStatus.OK.name();
//			data = t;
//		} 
		else if (t instanceof List) {
			this.code = HttpStatus.OK.value();
			this.message = HttpStatus.OK.name();
			@SuppressWarnings({ "unchecked", "rawtypes" })
			PageInfo<?> pageInfo = new PageInfo((List) t);
			paging = new Paging(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal());
			data = t;
		} else if (t instanceof Map) {
			this.code = HttpStatus.OK.value();
			this.message = HttpStatus.OK.name();
			data = t;
		} else if (t instanceof BadRequestException) {
			BadRequestException badRequestException = (BadRequestException) t;
			Integer code = badRequestException.getCode();
			this.code = code == null ? HttpStatus.BAD_REQUEST.value() : code;
			this.message = badRequestException.getMessageList().get(0);
			this.exception = null;
		} else if (t instanceof Exception) {
			Exception exception = (Exception) t;
			this.code = HttpStatus.BAD_REQUEST.value();
			this.message = exception.getMessage();
			this.exception = null;
		} else {
			this.code = HttpStatus.OK.value();
			this.message = HttpStatus.OK.name();
			data = t;
		}
		this.extraMap = extraMap;
	}

	@Data
	@AllArgsConstructor
	public static class Paging {
		private int pageNum;
		private int pageSize;
		private long total;
	}
}
